package com.example.wxback.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.wxback.model.ConfigInfo;
import com.example.wxback.service.ConfigService;
import com.example.wxback.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/config")
public class ConfigController {

    @Autowired
    private ConfigService configService;

    @GetMapping("/list")
    public JSONObject list(HttpServletRequest request) {
        return configService.list(CommonUtil.request2Json(request));
    }

    @PostMapping("/add")
    public JSONObject add(@RequestBody ConfigInfo configInfo) {

        if (configInfo.getId() != null) {
            ConfigInfo configInfoTable = configService.getById(configInfo.getId());
            if (configInfoTable == null) {
                return CommonUtil.errorJson("数据不存在");
            } else {
                configInfoTable.setContent(configInfo.getContent());
                configInfoTable.setUpdateDate(new Date());
                int count = configService.update(configInfoTable);
                if (count > 0) {
                    return CommonUtil.successJson("更新成功");
                } else {
                    return CommonUtil.successJson("更新失败");
                }
            }
        }
        configInfo.setCreateDate(new Date());
        configInfo.setUpdateDate(new Date());
        int count = configService.insert(configInfo);
        if (count > 0) {
            return CommonUtil.successJson("添加成功");
        } else {
            return CommonUtil.successJson("添加失败");
        }
    }

    @PostMapping("/update")
    public JSONObject update(@RequestBody ConfigInfo configInfo) {

        ConfigInfo configInfoTable = configService.getById(configInfo.getId());
        if (configInfoTable == null) {
            return CommonUtil.errorJson("数据不存在");
        } else {
            configInfoTable.setUpdateDate(new Date());
            int count = configService.update(configInfoTable);
            if (count > 0) {
                return CommonUtil.successJson("更新成功");
            } else {
                return CommonUtil.successJson("更新失败");
            }
        }
    }
}
